package com.zxd.interview.conrruentbook;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 加锁和交叉打印的场景
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.conrruentbook
 * @Description : 加锁和交叉打印的场景
 * @Create on : 2023/5/15 17:32
 **/
public class LockDemo {

    public static void main(String[] args) {
        new LockDemo().init();
    }

    static class Outputer {
        Lock lock = new ReentrantLock();

        /**
         * 一个个打印字符的场景
         * @param name
         */
        public void output(String name){
            int len = name.length();
            // 如果不加锁，多个线程会交叉打印内容
            lock.lock();
            try{
                for (int i = 0; i < len; i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println("");
            } finally {
                lock.unlock();
            }
        }/*
        不加锁的打印结果：
        牛奶糖
        旺仔
        牛旺仔
        奶糖
        旺牛奶糖
        仔
        旺仔
        牛奶糖
        牛奶糖
        旺仔
        */
    }

    private void init(){
        final Outputer outputer = new Outputer();
        new Thread(() ->{
           while(true){
               try {
                   Thread.sleep(5);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               outputer.output("旺仔");
           }
        }).start();

        new Thread(() ->{
            while(true){
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                outputer.output("牛奶糖");
            }
        }).start();
    }
}
